package srv

import (
	"context"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/asserts"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/beans"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/ferror"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/gorms"
	"gitee.com/shiqiyue/xd-bi/internal/modules/cr/model"
	"gitee.com/shiqiyue/xd-bi/internal/modules/cr/pkg/dbconn"
	"gitee.com/shiqiyue/xd-bi/internal/pkg/instance"
	"gorm.io/gorm"
)

func DictSqlInit() {
	srv := &DictSqlSrv{}
	err := beans.ProvideBean(srv)
	asserts.Nil(err, err)
}

type DictSqlSrv struct {
	ReportDbSrv *ReportDbSrv `inject:""`

	Db *gorm.DB `inject:""`
}

func (r *DictSqlSrv) DictMapByCategoryId(ctx context.Context, dictCategoryId string) (map[interface{}]string, error) {
	//SQL字典
	// 获取数据库链接
	dictionarySql, err := r.GetByDictCategoryId(ctx, dictCategoryId)
	if err != nil {
		return nil, ferror.Wrap("获取字典类型SQL失败", err)
	}
	reportDb := model.ReportDb{}
	err = r.ReportDbSrv.GetByUnionId(ctx, instance.GetDb(), dictionarySql.DbID, &reportDb)
	if err != nil {
		return nil, ferror.Wrap("获取报表数据库配置失败", err)
	}
	conn, err := dbconn.GetConn(ctx, reportDb)
	if err != nil {
		return nil, ferror.Wrap("获取数据库链接失败", err)
	}
	// 执行sql查询字典
	rs, err := r.ExecSql(ctx, conn, dictionarySql.AllSQL, nil)
	if err != nil {
		return nil, ferror.Wrap("执行SQL查询字典失败", err)
	}
	m := map[interface{}]string{}
	for _, dict := range rs {
		m[dict.Value] = dict.Text
	}
	return m, nil
}

func (s *DictSqlSrv) GetByDictCategoryId(ctx context.Context, DictCategoryId string) (*model.DictionarySQL, error) {
	db := gorms.GetDb(ctx, s.Db)
	r := &model.DictionarySQL{}
	err := db.Model(&model.DictionarySQL{}).Where(&model.DictionarySQL{DictionaryCategoryId: DictCategoryId}).Take(r).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		return nil, err
	}
	return r, nil
}

// 执行sql，查询字典
func (s DictSqlSrv) ExecSql(ctx context.Context, conn *gorm.DB, sql string, keyword *string) (ds []SqlDict, err error) {
	if keyword != nil {
		err = conn.Raw(sql, map[string]interface{}{"keyword": keyword}).Scan(&ds).Error
	} else {
		err = conn.Raw(sql).Scan(&ds).Error

	}
	return
}

func (r *DictSqlSrv) Add(ctx context.Context, d *model.DictionarySQL) error {
	db := gorms.GetDb(ctx, r.Db)
	err := db.Create(d).Error
	if err != nil {
		return ferror.Wrap("保存失败", err)
	}
	return nil
}

func (r *DictSqlSrv) Edit(ctx context.Context, d *model.DictionarySQL) error {
	db := gorms.GetDb(ctx, r.Db)
	err := db.Save(d).Error
	if err != nil {
		return ferror.Wrap("保存失败", err)
	}
	return nil
}

